package com.fjeld.server;

import com.fjeld.server.ssl.ServerStackLayer;
import org.apache.log4j.Logger;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * Created by IntelliJ IDEA.
 * User: fjeld
 * Date: 11/12/2011
 * Time: 14:33
 *
 * Loads any of the server stack layers
 */
public class ServerStackLoader
{
    private static final Logger LOGGER = Logger.getLogger(ServerStackLoader.class);

    public static ServerStackLayer loadServerStackLayer(String serverName, String sslClassName)
    {
        sslClassName = "com.fjeld.server.ssl.impl." + sslClassName;
        Class sslClass = null;
        ServerStackLayer ssl = null;
        try
        {
            sslClass = ClassLoader.getSystemClassLoader().loadClass(sslClassName);
            Constructor stateConstructor = sslClass.getConstructors()[0];
            Object[] args = new Object[0];
            ssl = (ServerStackLayer) stateConstructor.newInstance(args);
        } catch (ClassNotFoundException e)
        {
            LOGGER.error("Class not found: " + sslClassName + ".", e);
            System.exit(1);
        } catch (InvocationTargetException e)
        {
            LOGGER.error("InvocationTargetException when loading: " + sslClassName, e);
            System.exit(1);
        } catch (InstantiationException e)
        {
            LOGGER.error("InstantiationException when loading: " + sslClassName, e);
            System.exit(1);
        } catch (IllegalAccessException e)
        {
            LOGGER.error("IllegalAccessException when loading: " + sslClassName, e);
            System.exit(1);
        } catch (Exception e)
        {
            LOGGER.error("Exception when loading: " + sslClassName, e);
            System.exit(1);
        }

        return ssl;
    }
}
